// 页面路径：store/index.js 
import Vue from 'vue'
import Vuex from 'vuex'
import {
	login,
	getInfo
} from '@/api/login.js';
import {
	getToken,
	getOpenID,
	setOpenID,
	removeOpenID,
	setToken,
	removeToken
} from '@/utils/auth'
Vue.use(Vuex); //vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({

	state: {
		"token": getToken(),
		"isLogin": false,
		"open_id": getOpenID(),
		"userInfo": {

		}
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_OPENID: (state, open_id) => {
			state.open_id = open_id
		},
		SET_USERINFO: (state, data) => {
			state.userInfo = data
		},
	},
	actions: {
		logout({
			commit
		}) {
			commit('SET_TOKEN', "")
			commit('SET_OPENID', "")
			commit('SET_USERINFO', {})
			removeToken();
			removeOpenID();
		},
		// user login
		login({
			commit
		}, code) {
			console.log("执行到我o", code)
			return new Promise((resolve, reject) => {
				login(code).then(response => {
					console.log("请求返回结果,", response)
					const {
						data
					} = response
					commit('SET_TOKEN', data.token)
					commit('SET_OPENID', data.open_id)
					commit('SET_USERINFO', data)
					setOpenID(data.open_id)
					setToken(data.token)
					resolve(data)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// get user info
		getInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo(state.open_id).then(response => {
					const {
						data
					} = response

					if (!data) {
						reject('Verification failed, please Login again.')
					}
					commit('SET_USERINFO', data)
					resolve(data)
				}).catch(error => {
					reject(error)
				})
			})
		},
	}
})
export default store
